package data.factory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;

import tools.Pair;
import data.set.OfflineSet;
import data.set.implementation.OfflineSet_Memory ;
import preprocess.TextExtract ;

public class DocumentDirectoryOfflineSetFactory {
	
	private OfflineSet_Memory<String> allDocuments;
	//private String path2pos,path2neg;
	private String[] subdirectories;
	private int absoluteCPT;
	private OfflineSet_Memory<Integer> allLabels;
	private String path;
	
	
	public DocumentDirectoryOfflineSetFactory(String path) {
		
		this.path = path;
		File dir = new File(path);
		subdirectories = dir.list(new FilenameFilterDirectory());
				
		allDocuments = new OfflineSet_Memory<String>(); 
		allLabels = new OfflineSet_Memory<Integer>();
		absoluteCPT = 0;
			
	}
	
	/**
	 * Contrairement à l'autre constructeur, celui-ci prend comme subdirectories ceux donnés en paramêtre.
	 * @param subDirs
	 * @author simon
	 */
	public DocumentDirectoryOfflineSetFactory(String path, String[] classNames) {
		
		this.path=path ;
		this.subdirectories=classNames ;
		
		allDocuments = new OfflineSet_Memory<String>(); 
		allLabels = new OfflineSet_Memory<Integer>();
		absoluteCPT = 0;
	}
	
	
	public Pair<OfflineSet<String>, OfflineSet<Integer>> build() throws IOException{
		for(int i=0; i<subdirectories.length; i++)
		 loadOneDiretory(path+subdirectories[i], i);
		 
		 return new Pair<OfflineSet<String>, OfflineSet<Integer>>(allDocuments, allLabels);
	}
	
	private void loadOneDiretory(String path, int label) throws IOException{
		File directory = new File(path);
		
		if(!directory.isDirectory())
			throw new IOException("bad path to documents:"+directory);
		else
			System.out.println(directory+" added");
		
		String[] files = directory.list();
		
		for(String file:files){
			
			FileReader fr = new FileReader(new File(path+"/"+file));
			BufferedReader in = new BufferedReader(fr);
			String buf = "";
			String tot = "";
			while(buf != null){
				buf = in.readLine();
				if(buf != null)
					tot += buf;
			}
			
			/* Hop ! On insère la conversion des documents ! */
			tot=TextExtract.extract(tot) ;
			
			allDocuments.add(absoluteCPT,tot);
			allLabels.add(absoluteCPT,label);
			absoluteCPT++;
		}
		
	}
	
	
	private class FilenameFilterDirectory implements FilenameFilter{

		public boolean accept(File dir, String name) {
			File local= new File(dir.getAbsolutePath()+"/"+name);
			if(local.isDirectory()){
				return true;
			}
			return false;
		}
		
		
	}
}
